<template>
  <div>
    <el-row>
      <el-button type="primary" @click="openAddDialog">添加角色</el-button>
      <el-input v-model="searchQuery" placeholder="输入角色名称查询" @keyup.enter="searchRoles" style="width: 200px; margin-left: 20px;"></el-input>
      <el-button @click="searchRoles">查询</el-button>
    </el-row>
    <el-table :data="filteredRoles" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="name" label="角色名称" width="180"></el-table-column>
      <el-table-column prop="code" label="角色编号" width="180"></el-table-column>
      <el-table-column label="备注" width="240"></el-table-column>
      <el-table-column label="操作" width="240">
        <template v-slot:default="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" @click="openAssignResourcesDialog(scope.row)">资源分配</el-button>
          <el-button size="mini" @click="openAssignUsersDialog(scope.row)">用户分配</el-button>
          <el-button size="mini" @click="openViewPermissionsDialog(scope.row)">查看权限</el-button>
          <el-button size="mini" type="danger" @click="deleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" v-model:visible="addDialogVisible">
      <el-form :model="newRole" :rules="rules" ref="newRoleForm" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="newRole.name"></el-input>
        </el-form-item>
        <el-form-item label="角色编号" prop="code">
          <el-input v-model="newRole.code" @blur="checkRoleCode"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="newRole.remark"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addRole">添加</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" v-model:visible="editDialogVisible">
      <el-form :model="editRole" :rules="rules" ref="editRoleForm" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editRole.name"></el-input>
        </el-form-item>
        <el-form-item label="角色编号" prop="code">
          <el-input v-model="editRole.code"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editRole.remark"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateRole">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 资源分配对话框 -->
    <el-dialog title="资源分配" v-model:visible="assignResourcesDialogVisible" width="50%">
      <el-tree
          :data="resourceTree"
          show-checkbox
          node-key="id"
          ref="resourceTree"
          default-expand-all>
      </el-tree>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="assignResourcesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="assignResources">分配</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户分配对话框 -->
    <el-dialog title="用户分配" v-model:visible="assignUsersDialogVisible">
      <el-table :data="users" style="width: 100%;" @selection-change="handleUserSelection">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="用户名" width="180"></el-table-column>
      </el-table>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="assignUsersDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="assignUsers">分配</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看权限对话框 -->
    <el-dialog title="查看权限" v-model:visible="viewPermissionsDialogVisible">
      <el-tree
          :data="currentRolePermissions"
          node-key="id"
          ref="viewPermissionTree"
          default-expand-all
          disabled>
      </el-tree>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="viewPermissionsDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roles: [],
      filteredRoles: [],
      users: [],
      selectedUsers: [],
      searchQuery: '',
      addDialogVisible: false,
      editDialogVisible: false,
      assignResourcesDialogVisible: false,
      assignUsersDialogVisible: false,
      viewPermissionsDialogVisible: false,
      newRole: {
        name: '',
        code: '',
        remark: ''
      },
      editRole: {},
      existingRoleCodes: ['ADMIN', 'USER'], // 模拟现有的角色编号
      resourceTree: [], // 模拟资源树数据
      currentRolePermissions: [], // 当前角色的权限数据
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入角色编号', trigger: 'blur' },
          { validator: this.validateRoleCode, trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    openAddDialog() {
      this.addDialogVisible = true;
    },
    addRole() {
      this.$refs.newRoleForm.validate((valid) => {
        if (valid) {
          // 发送请求保存数据到 basic_role 表
          this.roles.push({ ...this.newRole });
          this.filteredRoles = this.roles;
          this.addDialogVisible = false;
          this.$message.success('角色添加成功');
        }
      });
    },
    openEditDialog(role) {
      this.editRole = { ...role };
      this.editDialogVisible = true;
    },
    updateRole() {
      this.$refs.editRoleForm.validate((valid) => {
        if (valid) {
          const index = this.roles.findIndex(r => r.code === this.editRole.code);
          if (index !== -1) {
            // 发送请求更新数据到 basic_role 表
            this.roles.splice(index, 1, { ...this.editRole });
            this.filteredRoles = this.roles;
            this.editDialogVisible = false;
            this.$message.success('角色更新成功');
          }
        }
      });
    },
    deleteRole(role) {
      // 发送请求删除 basic_role 表中的数据
      this.roles = this.roles.filter(r => r.code !== role.code);
      this.filteredRoles = this.roles;
      this.$message.success('角色删除成功');
    },
    checkRoleCode() {
      if (this.existingRoleCodes.includes(this.newRole.code)) {
        this.$message.error('角色编号重复，请重新输入');
        this.newRole.code = '';
      }
    },
    validateRoleCode(rule, value, callback) {
      if (this.existingRoleCodes.includes(value)) {
        callback(new Error('角色编号重复，请重新输入'));
      } else {
        callback();
      }
    },
    searchRoles() {
      this.filteredRoles = this.roles.filter(role => role.name.includes(this.searchQuery));
    },
    openAssignResourcesDialog(role) {
      this.currentRole = role;
      this.assignResourcesDialogVisible = true;
      // 加载资源树数据，模拟加载
      this.resourceTree = [
        { id: 1, label: '资源1', children: [{ id: 11, label: '资源1-1' }] },
        { id: 2, label: '资源2', children: [{ id: 21, label: '资源2-1' }] }
      ];
    },
    assignResources() {
      // 删除未使用的 checkedNodes 变量
      // const checkedNodes = this.$refs.resourceTree.getCheckedKeys();
      // 发送请求保存数据到 basic_role_resource 表和 basic_role_company 表
      this.$message.success('资源分配成功');
      this.assignResourcesDialogVisible = false;
    },
    openAssignUsersDialog(role) {
      if (!role.resources) {
        this.$message.error('角色需要分配资源后才可以分配');
        return;
      }
      this.currentRole = role;
      this.assignUsersDialogVisible = true;
      // 模拟加载用户列表
      this.users = [
        { name: '用户1', id: 1 },
        { name: '用户2', id: 2 },
        { name: '用户3', id: 3 }
      ];
    },
    handleUserSelection(selection) {
      this.selectedUsers = selection;
    },
    assignUsers() {
      if (this.selectedUsers.length === 0) {
        this.$message.error('请至少选择一个用户进行分配');
        return;
      }
      // 发送请求保存数据到 basic_user_role 表
      this.$message.success('用户分配成功');
      this.assignUsersDialogVisible = false;
    },
    openViewPermissionsDialog(role) {
      this.currentRole = role;
      this.viewPermissionsDialogVisible = true;
      // 加载当前角色的权限数据，模拟加载
      this.currentRolePermissions = [
        { id: 1, label: '资源1', children: [{ id: 11, label: '资源1-1' }] },
        { id: 2, label: '资源2', children: [{ id: 21, label: '资源2-1' }] }
      ];
    }
  },
  mounted() {
    // 模拟加载角色列表
    this.roles = [
      { name: '管理员', code: 'ADMIN', remark: '系统管理员', resources: true },
      { name: '用户', code: 'USER', remark: '普通用户', resources: false }
    ];
    this.filteredRoles = this.roles;
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>